package org.zuel.innovative.power;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component
@Log4j2
public class PowInterceptor implements HandlerInterceptor {

    @Autowired
    private Hostholder hostholder;

    @Autowired
    private Map<String, Integer> contro;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        String url=request.getRequestURI();
        Integer type=contro.get(url);
        if(type==null){
            return true;
        }
        User user =hostholder.getUser();
        Integer power;
        if(user==null){
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("普通请求，未登录");
            log.info("未登录");
            return false;
        }else{
            power=user.getType();
        }
        if(power>=type){
            return true;
        }else {
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write( "普通请求，你没有访问该功能的权限");
            log.info("权限不够");
            return false;
        }
    }

}
